/*----------------
This file reads in the 2007-09 panel data, and aligns these data to the FA.
Note: the main DFA data align the non-panel SCF data to the FA definitions. 
      This file aligns the SCF panel variables to the FA definitions. 

Overview of file: 
1. Read in the 2007-09 SCF panel

2. Find changes in financial and nonfinancial assets, changes in liabilities 2007-09.
Compare to the changes estimated by the DFA.

3. Create standard errors using boostrap replicates 

----------------*/

capture log close
capture clear
clear all
set more off
set matsize 11000
set maxvar 32767

log using [add log file path], replace


adopath + [add adopath, if using]

global datapath [add your filepath to the public SCF panel data (x and p variables), download from https://www.federalreserve.gov/econres/scf_2009p.htm#STATADAT]
global panelbull [add your filepath to the public bulletin variables for the SCF panel data, download from https://www.federalreserve.gov/econres/scf_2009p.htm#STATADATEX]

global reps=999

local path [add your filepath to the where this code will live]


// Get temp file of bootstrap replicates data file so that standard error loop below works
use [add your filepath to the public SCF panel bootstrap replicates, download from https://www.federalreserve.gov/econres/files/scf2009prw1s.zip] 
ren *,lower
tempfile bsrep2009
save `bsrep2009', replace
clear

global fadata [file path to a set of FA data referenced below]

// FA data
insheet using"$fadata/b101h_annual.csv"
tempfile balsheet
save `balsheet', replace
clear

// Most recent FA data 
insheet using "$fadata/fa_data.csv"
tempfile fadata
save `fadata', replace
clear

// The distributed DB pensions from the SCF
use "[DFA_DB.dta]", clear
keep if year==2007
gen year07=2007
tempfile DB
save `DB', replace


// 2007 SCF bulletin data
use [2007 SCF data, download from https://www.federalreserve.gov/econres/scf_2007.htm#STATADAT], clear
merge 1:1 xx1 x1 using [2007 SCF bulletin extract data, download from https://www.federalreserve.gov/econres/scf_2007.htm#STATADATEX], gen(m07)
* The part of savings accts that is in mmmf
gen mmmf_saving = 0
replace mmmf_saving = mmmf_saving + max(0,x3730) if inlist(x3732,4,30) & (x9259<11|x9259>13)
replace mmmf_saving = mmmf_saving + max(0,x3736) if inlist(x3738,4,30) & (x9260<11|x9260>13)
replace mmmf_saving = mmmf_saving + max(0,x3742) if inlist(x3744,4,30) & (x9261<11|x9261>13)
replace mmmf_saving = mmmf_saving + max(0,x3748) if inlist(x3750,4,30) & (x9262<11|x9262>13)
replace mmmf_saving = mmmf_saving + max(0,x3754) if inlist(x3756,4,30) & (x9263<11|x9263>13)
replace mmmf_saving = mmmf_saving + max(0,x3760) if inlist(x3762,4,30) & (x9264<11|x9264>13)
replace mmmf_saving = mmmf_saving + max(0,x3765) if inlist(x3762,4,30) & (x9264<11|x9264>13)

* The part of savings accts that is in mmda
gen mmda_saving = 0
replace mmda_saving = mmda_saving + max(0,x3730) if inlist(x3732,4,30) & (11<=x9259<=13)
replace mmda_saving = mmda_saving + max(0,x3736) if inlist(x3738,4,30) & (11<=x9260<=13)
replace mmda_saving = mmda_saving + max(0,x3742) if inlist(x3744,4,30) & (11<=x9261<=13)
replace mmda_saving = mmda_saving + max(0,x3748) if inlist(x3750,4,30) & (11<=x9262<=13)
replace mmda_saving = mmda_saving + max(0,x3754) if inlist(x3756,4,30) & (11<=x9263<=13)
replace mmda_saving = mmda_saving + max(0,x3760) if inlist(x3762,4,30) & (11<=x9264<=13)
replace mmda_saving = mmda_saving + max(0,x3765) if inlist(x3762,4,30) & (11<=x9264<=13)

* The part of checking accts that is in mmmf
gen mmmf_checking = 0
replace mmmf_checking = mmmf_checking+ max(0,x3506)*(x3507==1)*(x9113<11|x9113>13)
replace mmmf_checking = mmmf_checking+ max(0,x3510)*(x3511==1)*(x9114<11|x9114>13)
replace mmmf_checking = mmmf_checking+ max(0,x3514)*(x3515==1)*(x9115<11|x9115>13)
replace mmmf_checking = mmmf_checking+ max(0,x3518)*(x3519==1)*(x9116<11|x9116>13)
replace mmmf_checking = mmmf_checking+ max(0,x3522)*(x3523==1)*(x9117<11|x9117>13)
replace mmmf_checking = mmmf_checking+ max(0,x3526)*(x3527==1)*(x9118<11|x9118>13)
replace mmmf_checking = mmmf_checking+ max(0,x3529)*(x3527==1)*(x9118<11|x9118>13)

* The part of checking accts that is in mmda
gen mmda_checking = 0
replace mmda_checking = mmda_checking+ max(0,x3506)*(x3507==1)*(11<=x9113<=13)
replace mmda_checking = mmda_checking+ max(0,x3510)*(x3511==1)*(11<=x9114<=13)
replace mmda_checking = mmda_checking+ max(0,x3514)*(x3515==1)*(11<=x9115<=13)
replace mmda_checking = mmda_checking+ max(0,x3518)*(x3519==1)*(11<=x9116<=13)
replace mmda_checking = mmda_checking+ max(0,x3522)*(x3523==1)*(11<=x9117<=13)
replace mmda_checking = mmda_checking+ max(0,x3526)*(x3527==1)*(11<=x9118<=13)
replace mmda_checking = mmda_checking+ max(0,x3529)*(x3527==1)*(11<=x9118<=13)

keep xx1 x1 saving mmda mmmf checking mmmf_checking mmmf_saving mmda_checking mmda_saving wgt nwcat*
foreach x in saving mmda mmmf checking {
  ren `x' `x'07orig
}

// Savings accounts
* The share of accounts reported as money market or sweep that end up in mmmf
gen mmmf_sav_share = mmmf_saving / (mmmf_saving+mmda_saving)
* The share of accounts reported as money market or sweep that end up in mmda
gen mmda_sav_share = mmda_saving / (mmmf_saving+mmda_saving)

tabstat mmmf_sav_share mmda_sav_share [aw=wgt]
tabstat mmmf_sav_share mmda_sav_share [aw=wgt], by(nwcat)

// Checking accounts
* The share of accounts reported in checking sec that end up in mmmf
gen mmmf_check_share = mmmf_checking / (mmmf_checking+mmda_checking+checking)
* The share of accounts reported in checking sec that end up in mmda
gen mmda_check_share = mmda_checking / (mmmf_checking+mmda_checking+checking)

tabstat mmmf_check_share mmda_check_share [aw=wgt]
tabstat mmmf_check_share mmda_check_share [aw=wgt], by(nwcat)

drop wgt
tempfile orig07bull
save `orig07bull', replace

// 2009 panel data
insheet using $panelbull/SCFB2009panel.csv, clear
destring x7381, gen(X7381)
drop x7381 
ren *, upper
sort PP1 P1, stable

merge 1:1 PP1 P1 using $datapath/scf09pp6.dta, gen(merge_panel)

drop i I 
ren *, lower
drop j0* k0* j1* k1* j2* k2* j3* k3* j4* k4* j5* k5* j6* k6* j7* k7* j8* k8* j9* k9*
  
ren wgt09 wgt

merge 1:1 xx1 x1 using `orig07bull', gen(orig07merge)

// Implicate number
gen imp = mod(p1,10)

gen year=2009

/*Merge in B101h, and FA data including insurance*/
merge m:1 year using `balsheet', nogen

merge m:1 year using `fadata', nogen

gen year07 = 2007 if missing(x1)==0 // do this and year07 below to get to merge, keep the 2007 values of DBs etc...
keep if missing(x1)==0
merge 1:1 x1 year07 using `DB', nogen 

*clonevar age = age09
merge m:1 age using "$fadata/payout_annuities.dta", gen(m_ann)
keep if m_ann==3
merge m:1 x104 using "$fadata/payout_annuities_sp.dta", gen(m_annsp)
keep if m_annsp==3

/*------------------------------------
Financial Assets
------------------------------------*/
* A. Time deposits: sum of savings cds mmda and parts of IRA and trusts
*     e.g. replace scf_fa_time_dep = saving+cds+mmda+(0.10*iradebtsec)+(0.25*trustsdebtsec) if year==2010
* 1. Savings : we split out mmda, mmmf and savings from the savings account questions. 
*              But for here we just need to split out mmmf -- bc we combine savings and mmda bull variables.
*              MMMF are money mkt accounts held outside of banks. We don't ask detailed inst quex in 2009 so 
*              use 2007 instances of mmmf to help infer 2009 mmmf. See output from line 79 above -- it 
*              tells us the share of savings assets going to mmmf and mmda that are broken out form savings 
*              (ie code 4 or 30). See tabstat mmmf_sav_share mmda_sav_share [aw=wgt] -- 87% go to mmda and 13% to mmmf.
gen possible_mmmf07 = (x091012==1 | x091014==1)
gen possible_mmmf09 = (p091012==1 | p091014==1)
* About 11-18% of the most easily identifiable savings accounts are in mmmf (see tabstat mmmf_sav_share mmda_sav_share [aw=wgt] above), varies by wealth. Take 11-18% of possible 2009 total to mmmf
gen mmmf09 = 0 
replace mmmf09 = p091008*0.11 if possible_mmmf09==1 & nwcat09>=1 & nwcat09<=4
replace mmmf09 = p091008*0.18 if possible_mmmf09==1 & nwcat09==5

gen sav09 = msaving09
replace sav09 = msaving09-mmmf09 if mmmf09>0 & missing(mmmf09)==0 //take out mmmf part of msavings total (as would have been done in 2007 bulletin)

* Now checking. It is harder bc in 2009 we only ask total in checking, do not ask about sweep or mmkt. So
* Use 2007 breakout -- approx 1% of checking accounts reported in sec N end up in mmmf.
* (see lin 89 above tabstat mmmf_check_share mmda_check_share [aw=wgt])
replace mmmf09 = mmmf09 + 0.008*checking09 if nwcat09>=1 & nwcat09<=4
replace mmmf09 = mmmf09 + 0.04*checking09 if nwcat09==5

* now reconcile checking and savings for 2009. No need to break out mmda amounts in savings bc they stay with 
* savings in DFA, but need to break out mmda from checking bc mmda end up with savings in DFA (not checking).
replace checking09 = 0.90*checking09 // take out 1% for mmmf and 9% for mmda09

* Share of trusts in interest assets
gen trustdebtsec09 = 0
replace trustdebtsec09 = p6587 if p6591==2
replace trustdebtsec09 = p6587*(p091005/10000) if p6591==3

* Share of IRAs in interest assets
gen iradebtsec09 = 0
replace iradebtsec09 = p091003 if p091004==2
replace iradebtsec09 = p091003*(p6592/10000) if p091004==3

// Pull together: savings
gen scf_fa_time_dep09 = sav09+cds09+0.08*checking09 + 0.25*trustdebtsec09 + 0.10*iradebtsec09 if nwcat09>=1 & nwcat09<=4
replace scf_fa_time_dep09 = sav09+cds09+0.23*checking09 + 0.25*trustdebtsec09 + 0.10*iradebtsec09 if nwcat09==5

gen cash09 = ((p4020==63)*p4022) + ((p4024==63)*p4026) + ((p4028==63)*p4030)
gen scf_fa_foreign_dep09=0
replace scf_fa_foreign_dep09= fin09*0.06 if x7647==1 // no p7647 so use 2007 response
// Pull together: checkable+currency
gen scf_fa_check_fgn_dep_curr09 = checking09+cash09+scf_fa_foreign_dep09
// Pull together : mmmf (money market mutual funds)
gen scf_fa_mmmf_shares09 = mmmf09 + 0.40*iradebtsec09 + 0.10*trustdebtsec09

tabstat scf_fa_check_fgn_dep_curr09 scf_fa_time_dep09 scf_fa_mmmf_shares09 [aw=wgt], stats(sum)

// Debt securites: all bonds asked as one question, ,can't parse out across scf_fa_gov_muni_bnds and scf_fa_corp_for_bnds 
gen scf_fa_debtsec09 = bond09 + savbnd09 + 0.50*iradebtsec09 + 0.65*trustdebtsec09 
gen scf_fa_gov_muni_bnds09 = scf_fa_debtsec09 // just do this to get code to run
gen scf_fa_corp_for_bnds09 = 0 // just do this to get code to run

// mortgages & other loans owed 
gen scf_fa_mort_owed09 = p09401
gen scf_fa_othln_owed09 =  0 + call09 // x1404 no asked, this question not asked in panel 

**************************** RECONCILE LIFE INSURANCE **************************
summarize p4006[aw=wgt]
di r(sum)
local total_perm09=r(sum)


gen total_perm=.
replace total_perm=`total_perm09'


summarize p4003[aw=wgt] 
di r(sum)
local total_term09=r(sum)


gen total_term=.
replace total_term=`total_term09'


gen fa_life_reserv_gen=ga_reserves
gen fa_life_reserv_sep=fa_life_ins_perm_sep_reserves

gen fa_life_reserv_perm = perm_ratio*fa_life_reserv_gen+fa_life_reserv_sep
gen fa_life_reserv_term = (1-perm_ratio)*fa_life_reserv_gen

gen scf_fa_life_ins_perm09 = p4006*fa_life_reserv_perm/total_perm
gen scf_fa_life_ins_term09 = p4003*fa_life_reserv_term/total_term

gen scf_fa_life_ins09 = scf_fa_life_ins_term09 + scf_fa_life_ins_perm09


************************* RECONCILE CONSUMER DURABLES **************************

********************************************************************************
*                                                                              *
*                                                                              *
*                                                                              *
*                  fa_consumer_durables remains unadjusted                     * 
*                                                                              *
*                                                                              *
*                                                                              *
********************************************************************************

/* X4022 / X4026 / X4030: What is the total dollar value that you (and your family
			  living here) have in this asset?
X4020 / X4024 / X4028: What type of asset is it?*/

gen scf_fa_consumer_durables09=0
replace scf_fa_consumer_durables09=vehic09
replace scf_fa_consumer_durables09=scf_fa_consumer_durables09+p4022 if p4020<=25 | p4020==75 | p4020==76
replace scf_fa_consumer_durables09=scf_fa_consumer_durables09+p4026 if p4024<=25 | p4024==75 | p4024==76
replace scf_fa_consumer_durables09=scf_fa_consumer_durables09+p4030 if p4028<=25 | p4028==75 | p4028==76

/*---------------
Consumer Durables
1) vehicles
2) other_durables
----------------------*/

gen scf_fa_vehicles09=vehic09
gen scf_fa_other_durables09=scf_fa_consumer_durables09-scf_fa_vehicles09

/*------------------------------------
Real Estate Assets
 Need to modify code below for 2007 panel X vars and add 2009 panel P variables
 Refer to codebook (/mecs/scf3/final/scf2009p/doc/codebook.2009p.final)
  
------------------------------------*/

/* Tag households who have more or less properties than in 2007
NOTE:

	In 2009, households can report unlimited number of oresre (we ask how many residential properties the households own)
	In 2007, households can report up to 4 oresre (more than that is put in the mopup)
	So we can’t tell if households have more or less properties if they reported 4 properties in 2007 and more than 4 in 2009,
		we are currently assuming that the number of properties did not change in this case.
	If they have less properties, we assume they sold the last one first, and use the percent value from 
		the first few properties in 2007 to allocate value into 2009. 
	If they have more properties, we keep the value of the first few properties the same, and distribute the 
		difference between the 07 and 09 values equally into the additional properties

	Just some summary stats: about 80% of the sample has no change in number of oresre properties (that we can identify), 
		about 10% have 1-4 more, and about 10% have 1-4 less. This translates to 90%, 5% and 5% respectively when weighted. 
	
*/
* Generate variable for Number of RESRE properties in 2009 and 2007
g noresre09 = p09404
replace noresre09 = 0 if(p09404 == -1)

g noresre07 = (x1706 > 0) + (x1806 > 0) + (x1906 > 0) + (x2002 > 0)
	
* Generate variable for the number of additional properties
g new_oresre = min(noresre09, 4) - noresre07
 
* Generate variable to store value of each individual ORESRE property ni 2007
g oresre107 = (max(x1706,0)  * (x1705/10000)) 
g oresre207 = (max(x1806,0)  * (x1805/10000))
g oresre307 = (max(x1906,0)  * (x1905/10000)) 
g oresre407 = (max(x2002,0)) 

* Generate variable to store cost basis of each individual ORESRE property in 2007
g oresrecb107 = (max(x1709,0)  * (x1705/10000)) 
g oresrecb207 = (max(x1809,0)  * (x1805/10000))
g oresrecb307 = (max(x1909,0)  * (x1905/10000)) 
g oresrecb407 = (max(x2003,0))

** ALLOCATION WHEN NUMBER OF PROPERTIES STAYS CONSTANT OR DECRASES **
g pct1 = 0
g pct2 = 0
g pct3 = 0
g pct4 = 0

g pctcb1 = 0
g pctcb2 = 0
g pctcb3 = 0
g pctcb4 = 0

/* Allocate value of each home by percent if has 1 properties in 2009 */
replace pct1 = 1 if noresre09 == 1

replace pctcb1 = 1 if noresre09 == 1 

/* Allocate value of each home by percent if has 2 properties in 2009 */
replace pct1 = oresre107 / (oresre107 + oresre207) if (noresre09== 2 & new_oresre <= 0)
replace pct2 = oresre207 / (oresre107 + oresre207) if (noresre09== 2 & new_oresre <= 0)

replace pctcb1 = oresrecb107 / (oresrecb107 + oresrecb207) if (noresre09== 2 & new_oresre <= 0)
replace pctcb2 = oresrecb207 / (oresrecb107 + oresrecb207) if (noresre09== 2 & new_oresre <= 0)

/* Allocate value of each home by percent if has 3 properties in 2009 */
replace pct1 = oresre107 / (oresre107 + oresre207 + oresre307) if (noresre09== 3 & new_oresre <= 0)
replace pct2 = oresre207 / (oresre107 + oresre207 + oresre307) if (noresre09== 3 & new_oresre <= 0)
replace pct3 = oresre307 / (oresre107 + oresre207 + oresre307) if (noresre09== 3 & new_oresre <= 0)

replace pctcb1 = oresrecb107 / (oresrecb107 + oresrecb207 + oresrecb307) if (noresre09== 3 & new_oresre <= 0)
replace pctcb2 = oresrecb207 / (oresrecb107 + oresrecb207 + oresrecb307) if (noresre09== 3 & new_oresre <= 0)
replace pctcb3 = oresrecb307 / (oresrecb107 + oresrecb207 + oresrecb307) if (noresre09== 3 & new_oresre <= 0)


/* Allocate value of each home by percent if has 4 properties in 2009 */
replace pct1 = oresre107 / (oresre107 + oresre207 + oresre307 + oresre407) if (noresre09== 4 & new_oresre <= 0)
replace pct2 = oresre207 / (oresre107 + oresre207 + oresre307 + oresre407) if (noresre09== 4 & new_oresre <= 0)
replace pct3 = oresre307 / (oresre107 + oresre207 + oresre307 + oresre407) if (noresre09== 4 & new_oresre <= 0)
replace pct4 = oresre407 / (oresre107 + oresre207 + oresre307 + oresre407) if (noresre09== 4 & new_oresre <= 0)

replace pctcb1 = oresrecb107 / (oresrecb107 + oresrecb207 + oresrecb307 + oresrecb407) if (noresre09== 4 & new_oresre <= 0)
replace pctcb2 = oresrecb207 / (oresrecb107 + oresrecb207 + oresrecb307 + oresrecb407) if (noresre09== 4 & new_oresre <= 0)
replace pctcb3 = oresrecb307 / (oresrecb107 + oresrecb207 + oresrecb307 + oresrecb407) if (noresre09== 4 & new_oresre <= 0)
replace pctcb4 = oresrecb407 / (oresrecb107 + oresrecb207 + oresrecb307 + oresrecb407) if (noresre09== 4 & new_oresre <= 0)

/* Tie together */
g oresre109 = oresre09 * (pct1) 
g oresre209 = oresre09 * (pct2) 
g oresre309 = oresre09 * (pct3) 
g oresre409 = oresre09 * (pct4) 

gen oresrecb09 = p09406
g oresrecb109 = oresrecb09 * (pctcb1) 
g oresrecb209 = oresrecb09 * (pctcb2) 
g oresrecb309 = oresrecb09 * (pctcb3) 
g oresrecb409 = oresrecb09 * (pctcb4) 


** ALLOCATION WHEN NUMBER OF PROPERTIES INCREASES **

* Keep existing properties the same - if total value decreased even though number of properties increased, 
* 	take decrease in value out of last property
replace oresre109 = min(oresre107, oresre09) if(new_oresre > 0)
replace oresre209 = min(oresre207, (oresre09 - oresre109)) if(new_oresre > 0)
replace oresre309 = min(oresre307, (oresre09 - oresre109 - oresre209)) if(new_oresre > 0)
replace oresre409 = min(oresre407, (oresre09 - oresre109 - oresre209 - oresre309)) if(new_oresre > 0)


* Add extra value to next property 

* One more property
replace oresre409 = (oresre09 - oresre309 - oresre209 - oresre109) if(oresre409 == 0 & oresre309 > 0 & oresre209 > 0 & oresre109 > 0 & new_oresre == 1)
replace oresre309 = (oresre09 - oresre209 - oresre109) if(oresre309 == 0 & oresre209 > 0 & oresre109 > 0 & new_oresre == 1)
replace oresre209 = (oresre09 - oresre109) if(oresre209 == 0 & oresre109 > 0 & new_oresre == 1)
replace oresre109 = (oresre09) if(oresre109 == 0 & new_oresre == 1)

* Two more properties
replace oresre409 = (oresre09 - oresre109 - oresre209) / 2 if(oresre209 > 0 & new_oresre == 2)
replace oresre309 = (oresre09 - oresre109 - oresre209) / 2 if(oresre209 > 0 & new_oresre == 2)

replace oresre309 = (oresre09 - oresre109) / 2 if(oresre109 > 0 & new_oresre == 2)
replace oresre209 = (oresre09 - oresre109) / 2 if(oresre109 > 0  & new_oresre == 2)

replace oresre209 = (oresre09) / 2 if(oresre109 == 0 & new_oresre == 2)
replace oresre109 = (oresre09) / 2 if(oresre109 == 0 & new_oresre == 2)

* Three more properties
replace oresre409 = (oresre09 - oresre109) / 3 if(new_oresre == 3 & oresre109 > 0)
replace oresre309 = (oresre09 - oresre109) / 3 if(oresre309 == 0 & new_oresre == 3 & oresre109 > 0)
replace oresre209 = (oresre09 - oresre109) / 3 if(oresre209 == 0 & new_oresre == 3 & oresre109 > 0)

replace oresre309 = (oresre09) / 3 if(oresre109 == 0 & new_oresre == 3)
replace oresre209 = (oresre09) / 3 if(oresre109 == 0 & new_oresre == 3)
replace oresre109 = (oresre09) / 3 if(oresre109 == 0 & new_oresre == 3)

* Four more properties
replace oresre409 = (oresre09) / 4 if(new_oresre == 4)
replace oresre309 = (oresre09) / 4 if(oresre309 == 0 & new_oresre == 4)
replace oresre209 = (oresre09) / 4 if(oresre209 == 0 & new_oresre == 4)
replace oresre109 = (oresre09) / 4 if(oresre109 == 0 & new_oresre == 4)

* ALLOCATION INTO VACANT LAND
* Generate variable for Number of RESRE properties in 2009 and 2007
g vacant_land07 = oresre107 * (x1703 == 11) + oresre207 * (x1803 == 11) + oresre307 * (x1903 == 11)
g vacant_land09 = oresre109 * (x1703 == 11) + oresre209 * (x1803 == 11) + oresre309 * (x1903 == 11)

* Limit values to only oresre
replace oresre107 = oresre107 * inlist(x1703, 12, 14, 21, 22, 25, 40, 41, 42, 43, 44, 49, 50, 52, 999)
replace oresre207 = oresre207 * inlist(x1803, 12, 14, 21, 22, 25, 40, 41, 42, 43, 44, 49, 50, 52, 999)
replace oresre307 = oresre307 * inlist(x1803, 12, 14, 21, 22, 25, 40, 41, 42, 43, 44, 49, 50, 52, 999)

replace oresre109 = oresre109 * inlist(x1703, 12, 14, 21, 22, 25, 40, 41, 42, 43, 44, 49, 50, 52, 999)
replace oresre209 = oresre209 * inlist(x1803, 12, 14, 21, 22, 25, 40, 41, 42, 43, 44, 49, 50, 52, 999)
replace oresre309 = oresre309 * inlist(x1803, 12, 14, 21, 22, 25, 40, 41, 42, 43, 44, 49, 50, 52, 999)

* ALLOCATION INTO RENTAL/NONRENTAL
g rental_properties109 = 0
replace rental_properties109 = max(oresre109, 0) if inlist(x1703, 12, 14, 21, 22, 40, 41, 42, 43, 44, 49, 50, 52, 999)
replace rental_properties109 = 0 if x1729!=1

g rental_properties209=0
replace rental_properties209 = max(oresre209, 0) if inlist(x1803, 12, 14, 21, 22, 40, 41, 42, 43, 44, 49, 50, 52, 999)
replace rental_properties209 = 0 if x1829!=1

g rental_properties309=0
replace rental_properties309 = max(oresre309, 0) if inlist(x1903, 12, 14, 21, 22, 40, 41, 42, 43, 44, 49, 50, 52, 999)
replace rental_properties309 = 0 if x1929!=1

g rental_properties_more09 = 0
replace rental_properties_more09 = max(oresre409, 0) if x2009==1 

gen rental_properties107=0
replace rental_properties107 =max(x1706, 0)*(x1705/10000) if inlist(x1703, 12, 14, 21, 22, 40, 41, 42, 43, 44, 49, 50, 52, 999)
replace rental_properties107 =0 if x1729!=1

g rental_properties207=0
replace rental_properties207=max(x1806, 0)*(x1805/10000) if inlist(x1803, 12, 14, 21, 22, 40, 41, 42, 43, 44, 49, 50, 52, 999)
replace rental_properties207=0 if x1829!=1

g rental_properties307=0
replace rental_properties307=max(x1906, 0)*(x1905/10000) if inlist(x1903, 12, 14, 21, 22, 40, 41, 42, 43, 44, 49, 50, 52, 999)
replace rental_properties307=0 if x1929!=1

g rental_properties_more07=0
replace rental_properties_more07=max(0, x2002) if x2009==1 

g rentals07 = max(rental_properties107, 0) + max(rental_properties207, 0) + max(rental_properties307, 0) + max(rental_properties_more07, 0)
g rentals09 = max(rental_properties109, 0) + max(rental_properties209, 0) + max(rental_properties309, 0) + max(rental_properties_more09, 0)

g oresre_norent07=0
replace oresre_norent07=oresre07-rentals07

g oresre_norent09=0
replace oresre_norent09=oresre09-rentals09




* SCF FA REAL ESTATE 
g scf_fa_real_estate07 = max(houses07, 0) + max(oresre_norent07, 0) + max(vacant_land07, 0)
g scf_fa_real_estate09 = max(houses09, 0) + max(oresre_norent09, 0) + max(vacant_land09, 0)



*  SOME SUMMARY STATS TO CHECK VALIDITY
preserve
	g rentals_diff = rentals09 - rentals07 if(rentals09 > 0 | rentals07 > 0)
	g oresre_norent_diff = oresre_norent09 - oresre_norent07 if(oresre_norent09 > 0 | oresre_norent07 > 0)
	g vacant_land_diff = vacant_land09 - vacant_land07 if(vacant_land09 > 0 | vacant_land07 > 0)
	g scf_fa_real_estate_diff = scf_fa_real_estate09 - scf_fa_real_estate07 if(scf_fa_real_estate09 > 0 | scf_fa_real_estate07 > 0)

	replace rentals07 = . if rentals07 == 0 
	replace oresre_norent07 = . if oresre_norent07 == 0
	replace vacant_land07 = . if vacant_land07 == 0
	replace scf_fa_real_estate07 = . if scf_fa_real_estate07 == 0 

	replace rentals09 = . if rentals09 == 0 
	replace oresre_norent09 = . if oresre_norent09 == 0
	replace vacant_land09 = . if vacant_land09 == 0
	replace scf_fa_real_estate09 = . if scf_fa_real_estate09 == 0 

	tabstat rentals* oresre_norent* vacant_land* scf_fa_real_estate* [aw = wgt], stat(mean median count)

	foreach v in e107 e109 e207 e209 e307 e309 e407 e409 { 
		replace oresr`v' = . if oresr`v' <= 0 
	}

	foreach v in s107 s109 s207 s209 s307 s309 s_more07 s_more09 { 
	replace rental_propertie`v' = . if rental_propertie`v' <= 0 
	}

	tabstat oresre10* oresre20* oresre30* oresre40*, stat(mean median count)
	tabstat rental_properties10* rental_properties20* rental_properties30* rental_properties_more0*, stat(mean median count)

restore



/*------------------------------------
Business assets 
- Split into S corp and C corp  
* Same as for ORESRE excep non actively managed business which are allocated into scorp and ccorp by percent share in 2007 
------------------------------------*/
g bus107 = max(0,x3129) + max(0, x3124) - max(0, x3129) * (x3127 == 5) + max(0, x3121) * inlist(x3122, 1, 6)
g bus207 = max(0,x3229) + max(0, x3224) - max(0, x3229) * (x3127 == 5) + max(0, x3221) * inlist(x3222, 1, 6)
g bus307 = max(0,x3329) + max(0, x3324) - max(0, x3329) * (x3127 == 5) + max(0, x3321) * inlist(x3322, 1, 6)
g bus407 = max(0, x3335)
g bus507 = max(0, x3408) + max(0, x3412) + max(0, x3416) + max(0, x3420) + max(0, x3424) + max(0, x3428) 

g scorp107 = max(0,x3129) + max(0, x3124) - max(0, x3129) * (x3127 == 5) + max(0, x3121) * inlist(x3122, 1, 6) if(x3119 == 3)
g scorp207 = max(0,x3229) + max(0, x3224) - max(0, x3229) * (x3127 == 5) + max(0, x3221) * inlist(x3222, 1, 6) if(x3219 == 3)
g scorp307 = max(0,x3329) + max(0, x3324) - max(0, x3329) * (x3127 == 5) + max(0, x3321) * inlist(x3322, 1, 6) if(x3319 == 3)
* Nonactively managed 
g scorp407 = max(0, x3416)

g ccorp107 = max(0,x3129) + max(0, x3124) - max(0, x3129) * (x3127 == 5) + max(0, x3121) * inlist(x3122, 1, 6) if(x3119 == 4)
g ccorp207 = max(0,x3229) + max(0, x3224) - max(0, x3229) * (x3127 == 5) + max(0, x3221) * inlist(x3222, 1, 6) if(x3219 == 4)
g ccorp307 = max(0,x3329) + max(0, x3324) - max(0, x3329) * (x3127 == 5) + max(0, x3321) * inlist(x3322, 1, 6) if(x3319 == 4)
* Nonactively managed
g ccorp407 = max(0, x3420)

* Total nonactively managed businesses 
g totnonact07 = max(0, x3408) + max(0, x3412) + max(0, x3416) + max(0, x3420) + max(0, x3424) + max(0, x3428) + max(0, x8452)
g p_nonact_scorp = max(0, x3416) / totnonact07
g p_nonact_ccorp = max(0, x3420) / totnonact07

g numbus07 = x3105
g totbus07 = bus107 + bus207 + bus307 + bus407

g numbus09 = p3105
*g totbus09 = p09521
g totbus09 = max(0,p09521)+max(0,p09516)-max(0,p09518)*(p09519==5)+max(0,p09512)*(inlist(p09513,1,6))+max(0,p09528)

g difftotbus = totbus07 - totbus09
g diffnumbus = numbus07 - numbus09 


** ALLOCATION WHEN NUMBER OF BUSINESSES STAYS CONSTANT OR DECRASES [ACTIVELY MANAGED BUSINESSES ONLY]**
cap drop pct1 pct2 pct3 pct4
g pct1 = 0
g pct2 = 0
g pct3 = 0
g pct4 = 0

/* Allocate value of each business by percent if has 1 in 2009 */
replace pct1 = 1 if numbus09 == 1 

/* Allocate value of each business by percent if has 2 in 2009 */
replace pct1 = bus107 / (bus107 + bus207) if (numbus09== 2) // & diffnumbus <= 0) 
replace pct2 = bus207 / (bus107 + bus207) if (numbus09== 2) // & diffnumbus <= 0)

/* Allocate value of each home by percent if has 3 businesses in 2009 */
replace pct1 = bus107 / (bus107 + bus207 + bus307) if (numbus09== 3) //  & diffnumbus <= 0)
replace pct2 = bus207 / (bus107 + bus207 + bus307) if (numbus09== 3) //  & diffnumbus <= 0)
replace pct3 = bus307 / (bus107 + bus207 + bus307) if (numbus09== 3) //  & diffnumbus <= 0)

/* Allocate value of each home by percent if has 4 businesses in 2009 */
replace pct1 = bus107 / (bus107 + bus207 + bus307 + bus407) if (numbus09== 4) //  & diffnumbus <= 0)
replace pct2 = bus207 / (bus107 + bus207 + bus307 + bus407) if (numbus09== 4) //  & diffnumbus <= 0)
replace pct3 = bus307 / (bus107 + bus207 + bus307 + bus407) if (numbus09== 4) //  & diffnumbus <= 0)
replace pct4 = bus407 / (bus107 + bus207 + bus307 + bus407) if (numbus09== 4) //  & diffnumbus <= 0)
	
g bus109 = totbus09 * (pct1) 
g bus209 = totbus09 * (pct2) 
g bus309 = totbus09 * (pct3) 
g bus409 = totbus09 * (pct4) 

************************
* Allocation into S Corp 
g scorp109 = bus109 if(x3119 == 3)
g scorp209 = bus209 if(x3219 == 3)
g scorp309 = bus309 if(x3319 == 3)

* Non actively managed 
g scorp409 = p09528 * p_nonact_scorp

* Allocation into C Corp 
g ccorp109 = bus109 if(x3119 == 4)
g ccorp209 = bus209 if(x3219 == 4)
g ccorp309 = bus309 if(x3319 == 4)

* Non actively managed 
g ccorp409 = p09528 * p_nonact_ccorp


* SUMMARY STATS TO CHECK VALIDITY

preserve 
foreach v in scorp109 scorp209 scorp309 scorp409 scorp107 scorp207 scorp307 scorp407 ccorp109 ccorp209 ccorp309 ccorp409 ccorp107 ccorp207 ccorp307 ccorp407{
	replace `v' = . if `v' == 0
}
tabstat scorp109 scorp107 scorp209 scorp207 scorp309 scorp307 scorp409 scorp407 ccorp109 ccorp107 ccorp209 ccorp207 ccorp309 ccorp307 ccorp409 ccorp407, stat(median count mean)
restore

foreach v in scorp109 scorp209 scorp309 scorp409 scorp107 scorp207 scorp307 scorp407 ccorp109 ccorp209 ccorp309 ccorp409 ccorp107 ccorp207 ccorp307 ccorp407{
	replace `v' = 0 if missing(`v') == 1
}

gen sc_corp_stocks09=0
replace sc_corp_stocks09=p4022 if p4020==73 | p4020==74
replace sc_corp_stocks09=sc_corp_stocks09 + p4026 if p4024==73 | p4024==74 
replace sc_corp_stocks09=sc_corp_stocks09 + p4030 if p4028==73 | p4028==74

gen sc_corp_value09=scorp109 + scorp209 + scorp309 + scorp409 + ccorp109 + ccorp209 + ccorp309 + ccorp409 
gen sc_corp_equity09=sc_corp_value09 + sc_corp_stocks09

gen equity_non_corp_nw09=nnresre09+rentals09+bus09-sc_corp_value09 - vacant_land09

//need to take out cost basis but CB not asked in 2009. Find 2007 CB and interpolate to 2009 value

// Cost basis 2007
gen active_bus_cb1=0
gen active_bus_cb2=0
gen active_bus_cb3=0
gen active_bus_cb4=0

replace active_bus_cb1=max(0,x3130) if x3119!=3 | x3119!=4
replace active_bus_cb2=max(0,x3230) if x3219!=3 | x3219!=4
replace active_bus_cb3=max(0,x3330) if x3319!=3 | x3319!=4
replace active_bus_cb4=max(0,x3336)

// sc_corp cost basis 2007
gen active_bus_cb1_sc=0
gen active_bus_cb2_sc=0
gen active_bus_cb3_sc=0
gen active_bus_cb4_sc=0

replace active_bus_cb1_sc=max(0,x3130) if (x3119==3 | x3119==4)
replace active_bus_cb2_sc=max(0,x3230) if (x3219==3 | x3219==4)
replace active_bus_cb3_sc=max(0,x3330) if (x3319==3 | x3319==4)
replace active_bus_cb4_sc=max(0,x3336)

gen nonactive_bus_sc=0
replace nonactive_bus_sc=max(0,x3417) + max(0,x3421)

gen sc_corp_cb=active_bus_cb1_sc + active_bus_cb2_sc + active_bus_cb3_sc + active_bus_cb4_sc + nonactive_bus_sc 

// nonactive cost basis (all others)
gen nonactive_bus_cb1=0
gen nonactive_bus_cb2=0
gen nonactive_bus_cb3=0
gen nonactive_bus_cb4=0

replace nonactive_bus_cb1=max(0,x3409)
replace nonactive_bus_cb2=max(0,x3413)
replace nonactive_bus_cb3=max(0,x3425)
replace nonactive_bus_cb4=max(0,x3429)

gen bus_cb07=active_bus_cb1 + active_bus_cb2 + active_bus_cb3 + active_bus_cb4 + nonactive_bus_cb1 + nonactive_bus_cb2 + nonactive_bus_cb3 + nonactive_bus_cb4

// 2009 bus CB is 95% of 2007 CB (ad hoc)
gen bus_cb09=bus_cb07*0.95

gen rental_properties_cb1=0
gen rental_properties_cb2=0
gen rental_properties_cb3=0
gen rental_properties_cb4=0

**rentals using purchase price
replace rental_properties_cb1=x1709*(x1705/10000) if inlist(x1703, 12, 14, 21, 22, 40, 41, 42, 43, 44, 49, 50, 52, 999)
replace rental_properties_cb1=0 if x1729!=1
replace rental_properties_cb2=x1809*(x1805/10000) if inlist(x1803, 12, 14, 21, 22, 40, 41, 42, 43, 44, 49, 50, 52, 999)
replace rental_properties_cb2=0 if x1829!=1
replace rental_properties_cb3=x1909*(x1905/10000) if inlist(x1903, 12, 14, 21, 22, 40, 41, 42, 43, 44, 49, 50, 52, 999)
replace rental_properties_cb3=0 if x1929!=1
replace rental_properties_cb4=max(0, x2002) if x2009==1

gen rentals_cb07 = rental_properties_cb1 + rental_properties_cb2 + rental_properties_cb3 + rental_properties_cb4 

gen nnresre_cb1=0
gen nnresre_cb2=0
gen nnresre_cb3=0

replace nnresre_cb1= max(0,x1709)*(x1705/10000) if inlist(x1703, 1, 2, 3, 4, 5, 6, 7, 10, 11, 13, 15, 24, 45, 46, 47, 48, 51, 53, -7)
replace nnresre_cb2= max(0,x1809)*(x1805/10000) if inlist(x1803, 1, 2, 3, 4, 5, 6, 7, 10, 11, 13, 15, 24, 45, 46, 47, 48, 51, 53, -7)
replace nnresre_cb3= max(0,x1909)*(x1905/10000) if inlist(x1903, 1, 2, 3, 4, 5, 6, 7, 10, 11, 13, 15, 24, 45, 46, 47, 48, 51, 53, -7)

gen nnresre_cb07 = nnresre_cb1 + nnresre_cb2 + nnresre_cb3

gen equity_non_corp_cb07 = bus_cb07 + rentals_cb07 + nnresre_cb07

* 1/2 and 1/2 NW and CB for non_corp
gen scf_fa_equity_non_corp09 = .5*equity_non_corp_nw09 + .5*(0.95*equity_non_corp_cb07)
* use full equity value of S and C Corps (closer to FA concept) 
*replace scf_fa_corp_equity09 = scf_fa_corp_equity09 + sc_corp_equity09



// Corp eq
************************** RECONCILE CORPORATE EQUITIES ************************

gen scf_fa_corp_equity09 = stocks09 + irakh09 - iradebtsec09 + trusts09 - trustdebtsec09 + sc_corp_equity09


************************* RECONCILE MUTUAL FUND SHARES ************************

gen scf_fa_mut_fund_shares09 = nmmf09

************************* STOCKS + MUTUAL FUND SHARES ************************
tabstat scf_fa_corp_equity09  scf_fa_mut_fund_shares09  [aw=wgt], stats(sum)

gen scf_fa_corpeq_mut09 = scf_fa_corp_equity09 + scf_fa_mut_fund_shares09 


// Tally up aggregates form what created so far...
tabstat scf_fa_real_estate09 scf_fa_consumer_durables09 scf_fa_other_durables09 scf_fa_vehicles09 [aw=wgt], stats(sum)
tabstat scf_fa_debtsec09 scf_fa_check_fgn_dep_curr09 scf_fa_time_dep09 scf_fa_mmmf_shares09 scf_fa_gov_muni_bnds09 scf_fa_corp_for_bnds09 [aw=wgt], stats(sum)
tabstat scf_fa_mort_owed09 scf_fa_othln_owed09 scf_fa_corpeq_mut09 scf_fa_corp_equity09 scf_fa_mut_fund_shares09 scf_fa_equity_non_corp09 scf_fa_life_ins09  [aw=wgt], stats(sum)

// still need:  scf_fa_loans_assets09, scf_fa_pension09, scf_fa_misc_assets09
************************* RECONCILE PENSION ENTITLEMENTS ***********************

gen scf_fa_dc_assets09 = thrift09 + anypen09 // combined futpen and currpen questiosn into 1 in panel

/*------------------------------------
What to do about DBs?
1. same job? Keep & grow 2007 DB values
2. different job? Move old CJ DB PV to fut (unless not vested -- in plan <5 yrs) & add small amt if covered by DB on new job
3. retired? Same as 2.
------------------------------------*/
gen samejobR = 0
replace samejobR = 1 if p4115>x4115 | (p4115==x4115 & x4115>3)

gen diffjobR = 0
replace diffjobR = 1 if p4115<=2 & samejobR ==0

gen retiredR = 0
replace retiredR = 1 if x4115!=0 & p4115==0

gen samejobSP = 0
replace samejobSP = 1 if p4715>x4715 | (p4715==x4715 & x4715>3)

gen diffjobSP = 0
replace diffjobSP = 1 if p4715<=2 & samejobSP ==0

gen retiredSP = 0
replace retiredSP = 1 if x4715!=0 & p4715==0

// First, assume nothing changed 2007 to 2009 DB pen-wise, grow DB assets by 5% to account for growth (more yrs in plan etc) 2007-2009
gen scf_fa_db_assets09 = (currec_pv_dbamt_rtot + currec_pv_dbamt_sptot + future_pv_dbamt_rtot + future_pv_dbamt_sptot + curjob_pv_dbamt_r + curjob_pv_dbamt_sp)*1.05

replace scf_fa_db_assets09 = scf_fa_db_assets09 if samejobR==1 & samejobSP==1

* if new job then assume old DB goes to fut pen *unless* in plan less than 4 yrs in 2007
* also tack on new DB for new curr job -- use avg by income bins
tabstat income07, stats(min) by(inccat07 )
tabstat currec_pv_dbamt_rtot [aw=wgt] if x4115<=2 , by(inccat07) save
tabstatmat cjdb
gen cjdb07=cjdb[1,1] if income09<=22480
replace cjdb07=cjdb[2,1] if income09>22480 & income09<=39105
replace cjdb07=cjdb[3,1] if income09>39105 & income09<=62833
replace cjdb07=cjdb[4,1] if income09>62833 & income09<=103001
replace cjdb07=cjdb[5,1] if income09>103001 & income09<=149096
replace cjdb07=cjdb[6,1] if income09>149096 & missing(income09)==0

replace scf_fa_db_assets09 = ((currec_pv_dbamt_rtot + currec_pv_dbamt_sptot + future_pv_dbamt_rtot + future_pv_dbamt_sptot + curjob_pv_dbamt_sp)*1.05) + cjdb07 if samejobR==0 & (p091118==-1|p091118==1|p091118==2) & (x091118==-1|(x091118>=1 & x091118<=3)) & samejobSP==1
replace scf_fa_db_assets09 = ((currec_pv_dbamt_rtot + currec_pv_dbamt_sptot + future_pv_dbamt_rtot + future_pv_dbamt_sptot + curjob_pv_dbamt_sp)*1.05) + curjob_pv_dbamt_r + cjdb07 if samejobR==0 & (p091118==-1|p091118==1|p091118==2) & x091118>=4 & samejobSP==1

replace scf_fa_db_assets09 = ((currec_pv_dbamt_rtot + currec_pv_dbamt_sptot + future_pv_dbamt_rtot + future_pv_dbamt_sptot + curjob_pv_dbamt_r)*1.05) + cjdb07 if samejobR==1 & (p091718==-1|p091718==1|p091718==2) & (x091118==-1|(x091118>=1 & x091118<=3)) & samejobSP==0
replace scf_fa_db_assets09 = ((currec_pv_dbamt_rtot + currec_pv_dbamt_sptot + future_pv_dbamt_rtot + future_pv_dbamt_sptot + curjob_pv_dbamt_r)*1.05) + curjob_pv_dbamt_sp + cjdb07 if samejobR==1 & (p091718==-1|p091718==1|p091718==2) & x091718>=4 & samejobSP==0

// annuities
gen fa_annuit_factor_r09=0
replace fa_annuit_factor_r09 = p6577*fa_married if married09==1 
replace fa_annuit_factor_r09 = p6577*fa_single if married09==2 


gen fa_annuit_factor_sp09=0
replace fa_annuit_factor_sp09 = p6577*fa_married if married09==1 & p104>0 
replace fa_annuit_factor_sp09 = p6577*fa_single if married09==2 & p104>0



forvalues y=2007(1)2009{
summarize fa_annuit_factor_r[aw=wgt] if year==`y'
di r(sum)
local total_fa_annuit_r`y'=r(sum)
}

gen total_annuit_r=0
forvalues y=2007(1)2009{
replace total_annuit_r=`total_fa_annuit_r`y'' if year==`y'
}

forvalues y=2007(1)2009{
summarize fa_annuit_factor_sp[aw=wgt] if year==`y'
di r(sum)
local total_fa_annuit_sp`y'=r(sum)
}

gen total_annuit_sp=0
forvalues y=2007(1)2009{
replace total_annuit_sp=`total_fa_annuit_sp`y'' if year==`y'
}

gen scf_fa_annuit09 = 0
replace scf_fa_annuit09 = fa_ind_annuity_reserves*((fa_annuit_factor_r+fa_annuit_factor_sp)/(total_annuit_r+total_annuit_sp))

*gen scf_fa_annuit_sp=0
*replace scf_fa_annuit_sp = fa_ind_annuity_reserves*fa_annuit_factor_sp/total_annuit_sp

preserve 
collapse (sum) scf_fa_annuit09 [pw=wgt], by(year)
list
restore

tabstat scf_fa_mort_owed09 scf_fa_othln_owed09 scf_fa_corpeq_mut09 scf_fa_corp_equity09 scf_fa_mut_fund_shares09 scf_fa_equity_non_corp09 scf_fa_life_ins09 scf_fa_dc_assets0* scf_fa_db_assets09 scf_fa_annuit  [aw=wgt], stats(sum)
tabstat scf_fa_mort_owed09 scf_fa_othln_owed09 scf_fa_corpeq_mut09 scf_fa_corp_equity09 scf_fa_mut_fund_shares09 scf_fa_equity_non_corp09 scf_fa_life_ins09 scf_fa_dc_assets0* scf_fa_db_assets09 scf_fa_annuit  [aw=wgt], by(nwcat07)stats(sum)
tabstat scf_fa_mort_owed09 scf_fa_othln_owed09 scf_fa_corpeq_mut09 scf_fa_corp_equity09 scf_fa_mut_fund_shares09 scf_fa_equity_non_corp09 scf_fa_life_ins09 scf_fa_dc_assets0* scf_fa_db_assets09 scf_fa_annuit  [aw=wgt], by(nwcat09)stats(sum)


gen scf_fa_pension09 = scf_fa_dc_assets09+scf_fa_db_assets09+scf_fa_annuit09


// Misc assets
/*MISC ASSETS*/
_pctile income09 [aw=wgt], p(10 20 30 40 50 60 70 80 90)
gen incdec=.
replace incdec=1 if income09<=r(r1)
replace incdec=2 if income09>r(r1) & income09<=r(r2)
replace incdec=3 if income09>r(r2) & income09<=r(r3)
replace incdec=4 if income09>r(r3) & income09<=r(r4)
replace incdec=5 if income09>r(r4) & income09<=r(r5)
replace incdec=6 if income09>r(r5) & income09<=r(r6)
replace incdec=7 if income09>r(r6) & income09<=r(r7)
replace incdec=8 if income09>r(r7) & income09<=r(r8)
replace incdec=9 if income09>r(r8) & income09<=r(r9)
replace incdec=10 if income09>r(r9) & missing(income09)==0

*Per Joseph email Oct 12, 2018
gen other_health_ins_scale=.
replace other_health_ins_scale=0.038634 if incdec==1
replace other_health_ins_scale=0.031785 if incdec==2
replace other_health_ins_scale=0.05524 if incdec==3
replace other_health_ins_scale=0.081037 if incdec==4
replace other_health_ins_scale=0.099169 if incdec==5
replace other_health_ins_scale=0.108794 if incdec==6
replace other_health_ins_scale=0.125345 if incdec==7
replace other_health_ins_scale=0.142911 if incdec==8
replace other_health_ins_scale=0.148345 if incdec==9
replace other_health_ins_scale=0.16874 if incdec==10

foreach y in 2009{
summarize other_health_ins_scale [aw=wgt] if year==`y'
di r(sum)
local total_other_hi_scale`y'=r(sum)
}

gen total_other_hi_scale=.
foreach y in 2009{
replace total_other_hi_scale=`total_other_hi_scale`y'' if year==`y'
}

gen num_has_health_ins = 0
* Number of individuals in household (including NPEU) minus one for each type of person in household without health insurance
gen num_has_health_ins_gov =x101*(x6301==1)-(x6308==1)-(x6309==1)-(x6310==1)-(x6311==1)-(x6312==1)-(x6313==1)-(x6314==8|x6314==10|x6314==11)
replace num_has_health_ins_gov = 0 if num_has_health_ins_gov<=0
gen num_has_health_ins_priv =(x101 - num_has_health_ins_gov)*(x6315==1)-(x6330==1)-(x6331==1)-(x6332==1)-(x6333==1)-(x6334==1)-(x6335==1)-(x6336==8|x6336==10|x6336==11)
replace num_has_health_ins_priv = 0 if num_has_health_ins_priv<=0
replace num_has_health_ins = num_has_health_ins_gov + num_has_health_ins_priv

gen has_milit_retiree_health = 0
gen has_postal_retiree_health = 0

* Armed services retirees are eligible for retiree healthcare at 65
replace has_milit_retiree_health = (x5906==1)*(x14>=65) + (x6106==1)*(x19>=65) 

* Postal workers can retire at 56 and receive healthcare immediately
replace has_postal_retiree_health = (x7402==6370)*(x14>=56) + (x7412==6370)*(x19>=56) 

foreach y in 2009{
summarize houses09[aw=wgt] if year==`y'
di r(sum)
local total_houses`y'=r(sum)
summarize oresre09 [aw=wgt] if year==`y'
di r(sum)
local total_oresre`y'=r(sum)

}

gen total_houses=.
gen total_oresre=.
foreach y in 2009{
replace total_houses=`total_houses`y'' if year==`y'
replace total_oresre=`total_oresre`y'' if year==`y'
}

foreach y in 2009{
summarize vehic09[aw=wgt] if year==`y'
di r(sum)
local total_vehic`y'=r(sum)
}

gen total_vehic=.
foreach y in 2009{
replace total_vehic=`total_vehic`y'' if year==`y'
}

foreach y in 2009{
summarize num_has_health_ins[aw=wgt] if year==`y'
di r(sum)
local total_num_has_health_ins`y'=r(sum)
}

gen total_num_has_health_ins=.
foreach y in 2009{
replace total_num_has_health_ins=`total_num_has_health_ins`y'' if year==`y'
}

foreach y in 2009{
summarize has_milit_retiree_health[aw=wgt] if year==`y'
di r(sum)
local total_has_mil_ret_health`y'=r(sum)
}

gen total_has_milit_retiree_health=.
foreach y in 2009{
replace total_has_milit_retiree_health=`total_has_mil_ret_health`y'' if year==`y'
}

foreach y in 2009{
summarize has_postal_retiree_health[aw=wgt] if year==`y'
di r(sum)
local total_has_post_ret_health`y'=r(sum)
}

gen total_has_postal_retiree_health=.
foreach y in 2009{
replace total_has_postal_retiree_health=`total_has_post_ret_health`y'' if year==`y'
}

foreach y in 2009{
summarize x4005[aw=wgt] if year==`y'
di r(sum)
local total_perm_fv`y'=r(sum)
}

gen total_perm_fv=.
foreach y in 2009{
replace total_perm_fv=`total_perm_fv`y'' if year==`y'
}

gen fa_pc_houses = homes_payable*fa_pc_receivables
gen fa_pc_vehic = cars_payable*fa_pc_receivables
gen scf_fa_pc_houses = (houses09+oresre09)*fa_pc_houses/(total_houses+total_oresre)
gen scf_fa_pc_vehic = vehic09*fa_pc_vehic/total_vehic
gen scf_fa_pc_receivables = scf_fa_pc_houses + scf_fa_pc_vehic

gen fa_health_ins_reserves = fa_health_gen + fa_health_sep
gen scf_fa_health_ins_reserves = num_has_health_ins*fa_health_ins_reserves/total_num_has_health_ins

gen scf_fa_milit_retiree_health=0
replace scf_fa_milit_retiree_health = has_milit_retiree_health*fa_milit_retiree_health/total_has_milit_retiree_health if year >=2001
gen scf_fa_postal_retiree_health=0
replace scf_fa_postal_retiree_health = has_postal_retiree_health*fa_postal_retiree_health/total_has_postal_retiree_health if year>2004
gen scf_fa_gov_retiree_health = scf_fa_milit_retiree_health + scf_fa_postal_retiree_health

gen fa_life_div = fa_life_div_gen + fa_life_div_sep
gen scf_fa_life_ins_div = x4006*fa_life_div/total_perm

gen fa_life_claims_term = fa_life_claims*(1-perm_ratio)
gen fa_life_claims_perm = fa_life_claims*perm_ratio
gen scf_fa_life_ins_term_claim = x4003*fa_life_claims_term/total_term
gen scf_fa_life_ins_perm_claim = x4005*fa_life_claims_perm/total_perm_fv
gen scf_fa_life_ins_claims = scf_fa_life_ins_term_claim + scf_fa_life_ins_perm_claim
*gen fa_life_ins_claims = (x4003+x4005)*fa_life_claims/(total_term+total_perm_fv)

gen scf_oth_health_ins_reserves=other_health_ins_scale*ah_reserves/total_other_hi_scale
gen scf_fa_misc_assets09 = scf_fa_pc_receivables + scf_oth_health_ins_reserves + scf_fa_life_ins_div + ///
                         scf_fa_life_ins_claims + scf_fa_gov_retiree_health


// So far, aggregates... of assets
tabstat scf_fa_real_estate09 scf_fa_consumer_durables09 scf_fa_other_durables09 scf_fa_vehicles09 [aw=wgt], stats(sum)
tabstat scf_fa_debtsec09 scf_fa_check_fgn_dep_curr09 scf_fa_time_dep09 scf_fa_mmmf_shares09 scf_fa_gov_muni_bnds09 scf_fa_corp_for_bnds09 [aw=wgt], stats(sum)
tabstat scf_fa_mort_owed09 scf_fa_othln_owed09 scf_fa_corpeq_mut09 scf_fa_corp_equity09 scf_fa_mut_fund_shares09 scf_fa_pension09 scf_fa_equity_non_corp09 scf_fa_life_ins09 scf_fa_misc_assets [aw=wgt], stats(sum)

// Percentiles so far... of assets
_pctile networth09 [aw=wgt], p(50 70 90 99 99.9) 
gen dfacat=.
replace dfacat=1 if networth09<=r(r1) // Bottom 50
replace dfacat=2 if networth09>r(r1) & networth09<=r(r2) // Next 40
replace dfacat=3 if networth09>r(r2) & networth09<=r(r3) // Next 40
replace dfacat=4 if networth09>r(r3) & networth09<=r(r4) // 90-99
replace dfacat=5 if networth09>r(r4) & networth09<=r(r5) // Top 1, ex top 0.1
replace dfacat=6 if networth09>r(r5) & missing(networth09)==0 // Top 0.1

tabstat scf_fa_real_estate09 scf_fa_consumer_durables09 scf_fa_other_durables09 scf_fa_vehicles09 [aw=wgt], stats(sum) by(dfacat)
tabstat scf_fa_debtsec09 scf_fa_check_fgn_dep_curr09 scf_fa_time_dep09 scf_fa_mmmf_shares09 scf_fa_gov_muni_bnds09 scf_fa_corp_for_bnds09 [aw=wgt], stats(sum) by(dfacat)
tabstat scf_fa_mort_owed09 scf_fa_othln_owed09 scf_fa_corpeq_mut09 scf_fa_corp_equity09 scf_fa_mut_fund_shares09 scf_fa_pension09 scf_fa_equity_non_corp09 scf_fa_life_ins09 scf_fa_misc_assets [aw=wgt], stats(sum) by(dfacat)

gen finassets = scf_fa_debtsec09+scf_fa_check_fgn_dep_curr09+scf_fa_time_dep09+scf_fa_mmmf_shares09 ///
              + scf_fa_gov_muni_bnds09+scf_fa_corp_for_bnds09+scf_fa_mort_owed09+scf_fa_othln_owed09 ///
	      + scf_fa_corpeq_mut09+ scf_fa_pension09+scf_fa_life_ins09 
gen re = scf_fa_real_estate09
gen othernfin = scf_fa_consumer_durables09+scf_fa_other_durables09+scf_fa_vehicles09+scf_fa_equity_non_corp09+scf_fa_misc_assets

tabstat finassets re othernfin [aw=wgt], stats(sum) by(dfacat) save 
tabstatmat fig5



/*---------------------------------------------------------------------
LIABILITIES
---------------------------------------------------------------------*/

// Start with real estate debts


* Generate variable for Number of RESRE properties in 2009 and 2007
g nresdbt09 = p09404
replace nresdbt09 = 0 if(p09404 == -1)

g nresdbt07 = (x1706 > 0) + (x1806 > 0) + (x1906 > 0) + (x2002 > 0)
	
* Generate variable for the number of additional properties
g new_resdbt = min(nresdbt09, 4) - nresdbt07

 
* Generate variable to store value of each individual resdbt property in 2007
g mort1 = inlist(x1703, 12, 14, 21, 22, 25, 40, 41, 42, 43, 44, 49, 50, 52, 53, 999) * (x1705) * (x1705/1000)
g mort2 = inlist(x1803, 12, 14, 21, 22, 25, 40, 41, 42, 43, 44, 49, 50, 52, 53, 999) * (x1805) * (x1805/1000)
g mort3 = inlist(x1903, 12, 14, 21, 22, 25, 40, 41, 42, 43, 44, 49, 50, 52, 53, 999) * (x1905) * (x1905/1000)
g resdbt107 = max(x1417,0) + mort1
g resdbt207 = max(x1517,0) + mort2
g resdbt307 = max(x1617,0) + mort3
g resdbt407 = max(x1621,0) + x2006

* RESDBT : x1417 x1517 x1617 x1621 mort1 mort2 mort3 x2006

** ALLOCATION WHEN NUMBER OF PROPERTIES STAYS CONSTANT OR DECRASES **
cap drop pct1 pct2 pct3 pct4
g pct1 = 0
g pct2 = 0
g pct3 = 0
g pct4 = 0

/* Allocate value of each home by percent if has 1 properties in 2009 */
replace pct1 = 1 if nresdbt09 == 1 

/* Allocate value of each home by percent if has 2 properties in 2009 */
replace pct1 = resdbt107 / (resdbt107 + resdbt207) if (nresdbt09== 2 & new_resdbt <= 0)
replace pct2 = resdbt207 / (resdbt107 + resdbt207) if (nresdbt09== 2 & new_resdbt <= 0)

/* Allocate value of each home by percent if has 3 properties in 2009 */
replace pct1 = resdbt107 / (resdbt107 + resdbt207 + resdbt307) if (nresdbt09== 3 & new_resdbt <= 0)
replace pct2 = resdbt207 / (resdbt107 + resdbt207 + resdbt307) if (nresdbt09== 3 & new_resdbt <= 0)
replace pct3 = resdbt307 / (resdbt107 + resdbt207 + resdbt307) if (nresdbt09== 3 & new_resdbt <= 0)

/* Allocate value of each home by percent if has 4 properties in 2009 */
replace pct1 = resdbt107 / (resdbt107 + resdbt207 + resdbt307 + resdbt407) if(nresdbt09== 4 & new_resdbt <= 0)
replace pct2 = resdbt207 / (resdbt107 + resdbt207 + resdbt307 + resdbt407) if (nresdbt09== 4 & new_resdbt <= 0)
replace pct3 = resdbt307 / (resdbt107 + resdbt207 + resdbt307 + resdbt407) if (nresdbt09== 4 & new_resdbt <= 0)
replace pct4 = resdbt407 / (resdbt107 + resdbt207 + resdbt307 + resdbt407) if (nresdbt09== 4 & new_resdbt <= 0)
	
g resdbt109 = resdbt09 * (pct1) 
g resdbt209 = resdbt09 * (pct2) 
g resdbt309 = resdbt09 * (pct3) 
g resdbt409 = resdbt09 * (pct4) 

** ALLOCATION WHEN NUMBER OF PROPERTIES INCREASES **

* Keep existing properties the same - if total value decreased even though number of properties increased, 
* 	take decrease in value out of last property
replace resdbt109 = min(resdbt107, resdbt09) if(new_resdbt > 0)
replace resdbt209 = min(resdbt207, (resdbt09 - resdbt109)) if(new_resdbt > 0)
replace resdbt309 = min(resdbt307, (resdbt09 - resdbt109 - resdbt209)) if(new_resdbt > 0)
replace resdbt409 = min(resdbt407, (resdbt09 - resdbt109 - resdbt209 - resdbt309)) if(new_resdbt > 0)


* Add extra value to next property 

* One more property
replace resdbt409 = (resdbt09 - resdbt309 - resdbt209 - resdbt109) if(resdbt409 == 0 & resdbt309 > 0 & resdbt209 > 0 & resdbt109 > 0 & new_resdbt == 1)
replace resdbt309 = (resdbt09 - resdbt209 - resdbt109) if(resdbt309 == 0 & resdbt209 > 0 & resdbt109 > 0 & new_resdbt == 1)
replace resdbt209 = (resdbt09 - resdbt109) if(resdbt209 == 0 & resdbt109 > 0 & new_resdbt == 1)
replace resdbt109 = (resdbt09) if(resdbt109 == 0 & new_resdbt == 1)

* Two more properties
replace resdbt409 = (resdbt09 - resdbt109 - resdbt209) / 2 if(resdbt209 > 0 & new_resdbt == 2)
replace resdbt309 = (resdbt09 - resdbt109 - resdbt209) / 2 if(resdbt209 > 0 & new_resdbt == 2)

replace resdbt309 = (resdbt09 - resdbt109) / 2 if(resdbt109 > 0 & new_resdbt == 2)
replace resdbt209 = (resdbt09 - resdbt109) / 2 if(resdbt109 > 0  & new_resdbt == 2)

replace resdbt209 = (resdbt09) / 2 if(resdbt109 == 0 & new_resdbt == 2)
replace resdbt109 = (resdbt09) / 2 if(resdbt109 == 0 & new_resdbt == 2)

* Three more properties
replace resdbt409 = (resdbt09 - resdbt109) / 3 if(new_resdbt == 3 & resdbt109 > 0)
replace resdbt309 = (resdbt09 - resdbt109) / 3 if(resdbt309 == 0 & new_resdbt == 3 & resdbt109 > 0)
replace resdbt209 = (resdbt09 - resdbt109) / 3 if(resdbt209 == 0 & new_resdbt == 3 & resdbt109 > 0)

replace resdbt309 = (resdbt09) / 3 if(resdbt109 == 0 & new_resdbt == 3)
replace resdbt209 = (resdbt09) / 3 if(resdbt109 == 0 & new_resdbt == 3)
replace resdbt109 = (resdbt09) / 3 if(resdbt109 == 0 & new_resdbt == 3)

* Four more properties
replace resdbt409 = (resdbt09) / 4 if(new_resdbt == 4)
replace resdbt309 = (resdbt09) / 4 if(resdbt309 == 0 & new_resdbt == 4)
replace resdbt209 = (resdbt09) / 4 if(resdbt209 == 0 & new_resdbt == 4)
replace resdbt109 = (resdbt09) / 4 if(resdbt109 == 0 & new_resdbt == 4)

* ALLOCATION INTO VACANT LAND
* Generate variable for Number of RESRE properties in 2009 and 2007
g vacant_land_debt07 = resdbt107 * (x1703 == 11) + resdbt207 * (x1803 == 11) + resdbt307 * (x1903 == 11)
g vacant_land_debt09 = resdbt109 * (x1703 == 11) + resdbt209 * (x1803 == 11) + resdbt309 * (x1903 == 11)

* Limit values to only resdbt
replace resdbt107 = resdbt107 * inlist(x1703, 12, 14, 21, 22, 25, 40, 41, 42, 43, 44, 49, 50, 52, 999)
replace resdbt207 = resdbt207 * inlist(x1803, 12, 14, 21, 22, 25, 40, 41, 42, 43, 44, 49, 50, 52, 999)
replace resdbt307 = resdbt307 * inlist(x1803, 12, 14, 21, 22, 25, 40, 41, 42, 43, 44, 49, 50, 52, 999)

replace resdbt109 = resdbt109 * inlist(x1703, 12, 14, 21, 22, 25, 40, 41, 42, 43, 44, 49, 50, 52, 999)
replace resdbt209 = resdbt209 * inlist(x1803, 12, 14, 21, 22, 25, 40, 41, 42, 43, 44, 49, 50, 52, 999)
replace resdbt309 = resdbt309 * inlist(x1803, 12, 14, 21, 22, 25, 40, 41, 42, 43, 44, 49, 50, 52, 999)

* ALLOCATION INTO RENTAL/NONRENTAL -- already done above


g rental_debt07 = max(rental_properties107, 0) + max(rental_properties207, 0) + max(rental_properties307, 0) + max(rental_properties_more07, 0)
g rental_debt09 = max(rental_properties109, 0) + max(rental_properties209, 0) + max(rental_properties309, 0) + max(rental_properties_more09, 0)

g resdbt_norent07=0
replace resdbt_norent07 = resdbt07 - rental_debt07

g resdbt_norent09=0
replace resdbt_norent09 = resdbt09 - rental_debt09


* SCF FA REAL ESTATE 
gen scf_fa_mort_debt07 =max(mrthel07, 0) + max(resdbt_norent07, 0) + max(vacant_land_debt07, 0)
gen scf_fa_mort_debt09 =max(mrthel09, 0) + max(resdbt_norent09, 0) + max(vacant_land_debt09, 0)



/*----------------------------------------
Consumer credit
----------------------------------------*/

gen ccbalmult09=.
replace ccbalmult09 = ccbal09 * 1.265823 if incdec==1
replace ccbalmult09 = ccbal09 * 1.257862 if incdec==2
replace ccbalmult09 = ccbal09 * 1.30719 if incdec==3
replace ccbalmult09 = ccbal09 * 1.342282 if incdec==4
replace ccbalmult09 = ccbal09 * 1.369863 if incdec==5
replace ccbalmult09 = ccbal09 * 1.398601 if incdec==6
replace ccbalmult09 = ccbal09 * 1.428571 if incdec==7
replace ccbalmult09 = ccbal09 * 1.459854 if incdec==8
replace ccbalmult09 = ccbal09 * 1.550388 if incdec==9
replace ccbalmult09 = ccbal09 * 1.724138 if incdec==10

gen scf_fa_consumer_credit09 = ccbalmult09 + edninst09 + vehinst09 //+ othloc_non_dep_inst + oth_inst_non_dep_inst

/*DEFERRED AND UNPAID LIFE INSURANCE*/

gen fa_life_unpaid_term = fa_life_unpaid*(1-perm_ratio)
gen fa_life_unpaid_perm = fa_life_unpaid*perm_ratio
gen scf_fa_life_ins_term_unpaid = p4003*fa_life_unpaid_term/total_term
gen scf_fa_life_ins_perm_unpaid = p4006*fa_life_unpaid_perm/total_perm

gen scf_fa_life_ins_unpaid = scf_fa_life_ins_term_unpaid + scf_fa_life_ins_perm_unpaid

/*-----------------------------------------------------------
// Get into FA land aggregates
-----------------------------------------------------------*/



/*ADDITIONAL AGGREGATES BASED ON FA BALANCE SHEET*/
gen scf_fa_dc_assets_wgted = scf_fa_dc_assets09*wgt
egen scf_fa_dc_assets_tot=sum(scf_fa_dc_assets_wgted), by(year)
gen scf_fa_pension_tot = (fa_dc_aggregate*scf_fa_dc_assets_wgted/scf_fa_dc_assets_tot) /// 
                       + (scf_fa_db_assets + annuities_r + annuities_sp)*wgt + scf_fa_annuit*wgt
qui g long scf_fa_pension = scf_fa_pension_tot/wgt

gen scf_fa_corpeq_mut = scf_fa_corp_equity09 + scf_fa_mut_fund_shares09	
gen scf_fa_nonfin = scf_fa_real_estate09 + scf_fa_consumer_durables09
gen scf_fa_loans_assets = scf_fa_mort_owed09 + scf_fa_othln_owed09
replace scf_fa_life_ins09 = 0 if scf_fa_life_ins09 < 0

gen scf_fa_fin = scf_fa_debtsec09 + scf_fa_loans_assets + scf_fa_check_fgn_dep_curr09 ///
               + scf_fa_time_dep09 + scf_fa_mmmf_shares09 + scf_fa_corpeq_mut09 + scf_fa_pension09 ///
               + scf_fa_equity_non_corp09 + scf_fa_life_ins09 + scf_fa_misc_assets09

gen scf_fa_assets = scf_fa_nonfin + scf_fa_fin

gen scf_fa_loans_liab = scf_fa_mort_debt09 + scf_fa_consumer_credit09 //+ scf_fa_dep_inst_loans+ scf_fa_oth_loans
gen scf_fa_liab = scf_fa_loans_liab + scf_fa_life_ins_unpaid
gen scf_fa_nw = scf_fa_assets - scf_fa_liab







*stop

/*SCALE TO FA VALUES*/
// later on add scf_fa_mort_debt scf_fa_consumer_credit scf_fa_oth_loans scf_fa_dep_inst_loans scf_fa_edninst scf_fa_life_ins_unpaid
ren scf_fa_check_fgn_dep_curr09 scf_fa_check_fdep_curr09
foreach x in scf_fa_real_estate09 scf_fa_consumer_durables09 scf_fa_check_fdep_curr09 scf_fa_time_dep09 ///
             scf_fa_mmmf_shares09 scf_fa_gov_muni_bnds09 scf_fa_corp_for_bnds09 scf_fa_othln_owed09 ///
	     scf_fa_mort_owed09 scf_fa_corpeq_mut09 scf_fa_pension09 scf_fa_equity_non_corp09 ///
	     scf_fa_misc_assets09    ///
	     scf_fa_life_ins09 scf_fa_mort_debt09 scf_fa_consumer_credit09 scf_fa_life_ins_unpaid {
	gen `x'_wgted=`x'*wgt
}
egen scf_fa_real_estate_tot=sum(scf_fa_real_estate09_wgted), by(year)
egen scf_fa_consumer_durables_tot=sum(scf_fa_consumer_durables09_wgted), by(year)
egen scf_fa_check_fgn_dep_curr_tot=sum(scf_fa_check_fdep_curr09_wgted), by(year)
egen scf_fa_time_dep_tot=sum(scf_fa_time_dep09_wgted), by(year)
egen scf_fa_mmmf_shares_tot=sum(scf_fa_mmmf_shares09_wgted), by(year)
egen scf_fa_gov_muni_bnds_tot=sum(scf_fa_gov_muni_bnds09_wgted), by(year)
egen scf_fa_corp_for_bnds_tot=sum(scf_fa_corp_for_bnds09_wgted), by(year)
egen scf_fa_othln_owed_tot=sum(scf_fa_othln_owed09_wgted), by(year)
egen scf_fa_mort_owed_tot=sum(scf_fa_mort_owed09_wgted), by(year)
egen scf_fa_corpeq_mut_tot=sum(scf_fa_corpeq_mut09_wgted), by(year)

egen scf_fa_equity_non_corp_tot=sum(scf_fa_equity_non_corp09_wgted), by(year)
egen scf_fa_misc_assets_tot=sum(scf_fa_misc_assets09_wgted), by(year)
egen scf_fa_mort_debt_tot=sum(scf_fa_mort_debt09_wgted), by(year)
egen scf_fa_consumer_credit_tot=sum(scf_fa_consumer_credit09_wgted), by(year)
egen scf_fa_life_ins_unpaid_tot=sum(scf_fa_life_ins_unpaid_wgted), by(year)
egen scf_fa_life_ins_tot=sum(scf_fa_life_ins09_wgted), by(year)


gen scf_fa_wgted = scf_fa_real_estate09_wgted + scf_fa_consumer_durables09_wgted + ///
                 scf_fa_check_fdep_curr09_wgted + scf_fa_time_dep09_wgted + scf_fa_mmmf_shares09_wgted + ///
		 scf_fa_gov_muni_bnds09_wgted + scf_fa_corp_for_bnds09_wgted + scf_fa_othln_owed09_wgted + ///
		 scf_fa_mort_owed09_wgted + scf_fa_corpeq_mut09_wgted + scf_fa_equity_non_corp09_wgted + ///
		 scf_fa_misc_assets09_wgted + scf_fa_life_ins09_wgted	 

/*--------------------------------
Computed similar to recon below, but not called that here 
so that it will feed into Forbes part below as just 
component names
--------------------------------*/
// nonfin and components
gen real_estate = fa_real_estate*scf_fa_real_estate09_wgted/scf_fa_real_estate_tot 
gen consumer_durables = fa_con_durables*scf_fa_consumer_durables09_wgted/scf_fa_consumer_durables_tot
gen nonfinasset = fa_real_estate*scf_fa_real_estate09_wgted/scf_fa_real_estate_tot + ///
                   fa_con_durables*scf_fa_consumer_durables09_wgted/scf_fa_consumer_durables_tot

// fin and components
gen debtsec = (fa_us_gov_muni*scf_fa_gov_muni_bnds09_wgted/scf_fa_gov_muni_bnds_tot + ///
                    fa_corp_for_bonds*scf_fa_corp_for_bnds09_wgted/scf_fa_corp_for_bnds_tot)
gen gov_muni_bnds = fa_us_gov_muni*scf_fa_gov_muni_bnds09_wgted/scf_fa_gov_muni_bnds_tot 
gen corp_for_bnds = fa_corp_for_bonds*scf_fa_corp_for_bnds09_wgted/scf_fa_corp_for_bnds_tot
*need bc all are .s in 2009 land
replace corp_for_bnds=0 if missing(corp_for_bnds)==1

gen loans_assets = (fa_morts_owed*scf_fa_mort_owed09_wgted/scf_fa_mort_owed_tot + ///
                         fa_oth_loans*scf_fa_othln_owed09_wgted/scf_fa_othln_owed_tot)
gen mort_owed = fa_morts_owed*scf_fa_mort_owed09_wgted/scf_fa_mort_owed_tot 
gen othln_owed = fa_oth_loans*scf_fa_othln_owed09_wgted/scf_fa_othln_owed_tot
			 
gen liqfin =  (fa_check_curr*scf_fa_check_fdep_curr09_wgted/scf_fa_check_fgn_dep_curr_tot + ///
		     fa_time_dep*scf_fa_time_dep09_wgted/scf_fa_time_dep_tot + ///
		     fa_mmfs*scf_fa_mmmf_shares09_wgted/scf_fa_mmmf_shares_tot)
gen check_fgn_dep_curr = fa_check_curr*scf_fa_check_fdep_curr09_wgted/scf_fa_check_fgn_dep_curr_tot 
gen time_dep =  fa_time_dep*scf_fa_time_dep09_wgted/scf_fa_time_dep_tot
gen mmmf_shares = fa_mmfs*scf_fa_mmmf_shares09_wgted/scf_fa_mmmf_shares_tot

gen corpeq_mut =  (fa_corp_equ_mfs*scf_fa_corpeq_mut09_wgted/scf_fa_corpeq_mut_tot )
gen pension =	 scf_fa_pension_tot

gen long dc_assets = fa_dc_aggregate*scf_fa_dc_assets_wgted/scf_fa_dc_assets_tot
g long dbassets = (scf_fa_db_assets + annuities_r + annuities_sp)*wgt 
replace annuit09 = scf_fa_annuit09*wgt


gen equity_non_corp =  (fa_non_corp_eq*scf_fa_equity_non_corp09_wgted/scf_fa_equity_non_corp_tot )

gen misc_assets = fa_misc_assets*scf_fa_misc_assets09_wgted/scf_fa_misc_assets_tot
*gen life_ins = (ga_reserve + fa_life_ins_perm_sep)*scf_fa_life_ins_wgted/scf_fa_life_ins_tot 
gen life_ins = scf_fa_life_ins09*wgt

gen finasset = check_fgn_dep_curr + time_dep + mmmf_shares + gov_muni_bnds + corp_for_bnds ///
              + othln_owed + mort_owed + corpeq_mut + pension + equity_non_corp + misc_assets + life_ins

gen assets_recon = (nonfinasset + finasset)/wgt
tabstat assets_recon [aw=wgt], stats(sum)

// Liab
gen loans_liab = fa_morts*scf_fa_mort_debt09_wgted/scf_fa_mort_debt_tot + ///
		       fa_cons_cred*scf_fa_consumer_credit09_wgted/scf_fa_consumer_credit_tot 


gen mort_liab = fa_morts*scf_fa_mort_debt09_wgted/scf_fa_mort_debt_tot
gen concr_liab = fa_cons_cred*scf_fa_consumer_credit09_wgted/scf_fa_consumer_credit_tot 
gen lins_liab = fa_unpaid_life_ins*scf_fa_life_ins_unpaid_wgted/scf_fa_life_ins_unpaid_tot	
     		     
gen liab_recon = (loans_liab + fa_unpaid_life_ins*scf_fa_life_ins_unpaid_wgted/scf_fa_life_ins_unpaid_tot)/wgt
gen recon_nw = (assets_recon - liab_recon)/wgt
gen recon_nw_wgt = (assets_recon - liab_recon)

tabstat *recon*, stats(sum)
tabstat *recon* [aw=wgt], stats(sum)

/*drop dfacat
_pctile assets_recon [aw=wgt], p(50 70 90 99 99.9)
gen dfacat=1 if assets_recon<=r(r1) // Bottom 50
replace dfacat=2 if assets_recon>r(r1) & assets_recon<=r(r2) // Next 20 (50-70)
replace dfacat=3 if assets_recon>r(r2) & assets_recon<=r(r3) // Next 20 (70-90)
replace dfacat=4 if assets_recon>r(r3) & assets_recon<=r(r4) // 90-99
replace dfacat=5 if assets_recon>r(r4) & assets_recon<=r(r5) // Top 1, ex top 0.1
replace dfacat=6 if assets_recon>r(r5) & missing(assets_recon)==0 // Top 0.1*/

drop dfacat
_pctile recon_nw_wgt [aw=wgt], p(50 70 90 99 99.9)
gen dfacat=1 if recon_nw_wgt<=r(r1) // Bottom 50
replace dfacat=2 if recon_nw_wgt>r(r1) & recon_nw_wgt<=r(r2) // Next 20 (50-70)
replace dfacat=3 if recon_nw_wgt>r(r2) & recon_nw_wgt<=r(r3) // Next 20 (70-90)
replace dfacat=4 if recon_nw_wgt>r(r3) & recon_nw_wgt<=r(r4) // 90-99
replace dfacat=5 if recon_nw_wgt>r(r4) & recon_nw_wgt<=r(r5) // Top 1, ex top 0.1
replace dfacat=6 if recon_nw_wgt>r(r5) & missing(recon_nw)==0 // Top 0.1*/


// Broad asset and liab aggregates--aligned to FA--by nw cat
gen othnonfinasset=nonfinasset-real_estate
gen bus_eq = corpeq_mut +  equity_non_corp
gen othfin = finasset - bus_eq

gen nw = bus_eq+othfin+nonfinasset-mort_liab-concr_liab

label define dfacatl 1 "Bot50" 2 "50-70" 3 "70-90" 4 "90-99" 5 "99-99.9" 6 "Top0.1"
label values dfacat dfacatl 

// Aggregates for Figure 7

tabstat bus_eq othfin nonfinasset mort_liab concr_liab nw, stats(sum) by(dfacat) save
tabstatmat fig5

/******************************************************
* Begin Standard error computation
******************************************************/

// Share held by top `ptile' percent by implicate
forvalues i = 1(1)5 {
  tabstat bus_eq othfin nonfinasset mort_liab concr_liab nw if imp==`i', stats(sum) by(dfacat) save 
  tabstatmat fig5_imp`i'
  forvalues row = 1(1)6 {
	mat fig5_r`row'c1_imp`i' = fig5_imp`i'[`row',1]
	mat fig5_r`row'c2_imp`i' = fig5_imp`i'[`row',2]
	mat fig5_r`row'c3_imp`i' = fig5_imp`i'[`row',3]
	mat fig5_r`row'c4_imp`i' = fig5_imp`i'[`row',4]
	mat fig5_r`row'c5_imp`i' = fig5_imp`i'[`row',5]
	mat fig5_r`row'c6_imp`i' = fig5_imp`i'[`row',6]
  }
}

// matrix of agg assets by dfacat (rows = dfacat, cols = asset class) across 5 implicates
forvalues row = 1(1)6 {
   matrix fig5_r`row'c1 = (fig5_r`row'c1_imp1\fig5_r`row'c1_imp2\fig5_r`row'c1_imp3\fig5_r`row'c1_imp4\fig5_r`row'c1_imp5)
   matrix fig5_r`row'c2 = (fig5_r`row'c2_imp1\fig5_r`row'c2_imp2\fig5_r`row'c2_imp3\fig5_r`row'c2_imp4\fig5_r`row'c2_imp5)
   matrix fig5_r`row'c3 = (fig5_r`row'c3_imp1\fig5_r`row'c3_imp2\fig5_r`row'c3_imp3\fig5_r`row'c3_imp4\fig5_r`row'c3_imp5)
   matrix fig5_r`row'c4 = (fig5_r`row'c4_imp1\fig5_r`row'c4_imp2\fig5_r`row'c4_imp3\fig5_r`row'c4_imp4\fig5_r`row'c4_imp5)
   matrix fig5_r`row'c5 = (fig5_r`row'c5_imp1\fig5_r`row'c5_imp2\fig5_r`row'c5_imp3\fig5_r`row'c5_imp4\fig5_r`row'c5_imp5)
   matrix fig5_r`row'c6 = (fig5_r`row'c6_imp1\fig5_r`row'c6_imp2\fig5_r`row'c6_imp3\fig5_r`row'c6_imp4\fig5_r`row'c6_imp5)
}


// mean agg assets by dfa cat over the 5 implicates
forvalues row = 1(1)6 {
  matrix fig5_r`row'c1mn = fig5_r`row'c1'*J(5,1,1/5)
  matrix fig5_r`row'c2mn = fig5_r`row'c2'*J(5,1,1/5)
  matrix fig5_r`row'c3mn = fig5_r`row'c3'*J(5,1,1/5)
  matrix fig5_r`row'c4mn = fig5_r`row'c4'*J(5,1,1/5)
  matrix fig5_r`row'c5mn = fig5_r`row'c5'*J(5,1,1/5)
  matrix fig5_r`row'c6mn = fig5_r`row'c6'*J(5,1,1/5)
}

// imputation variance over 5 implicates
forvalues row = 1(1)6 {
  mata: impvar=quadvariance(st_matrix("fig5_r`row'c1"))
  mata: st_matrix("ivarfig5_r`row'c1",impvar)
  mat ivarfig5_r`row'c1=vecdiag(ivarfig5_r`row'c1)

  mata: impvar=quadvariance(st_matrix("fig5_r`row'c2"))
  mata: st_matrix("ivarfig5_r`row'c2",impvar)
  mat ivarfig5_r`row'c2=vecdiag(ivarfig5_r`row'c2)
  
  mata: impvar=quadvariance(st_matrix("fig5_r`row'c3"))
  mata: st_matrix("ivarfig5_r`row'c3",impvar)
  mat ivarfig5_r`row'c3=vecdiag(ivarfig5_r`row'c3)
  
    mata: impvar=quadvariance(st_matrix("fig5_r`row'c4"))
  mata: st_matrix("ivarfig5_r`row'c4",impvar)
  mat ivarfig5_r`row'c4=vecdiag(ivarfig5_r`row'c4)
  
    mata: impvar=quadvariance(st_matrix("fig5_r`row'c5"))
  mata: st_matrix("ivarfig5_r`row'c5",impvar)
  mat ivarfig5_r`row'c5=vecdiag(ivarfig5_r`row'c5)
  
  mata: impvar=quadvariance(st_matrix("fig5_r`row'c6"))
  mata: st_matrix("ivarfig5_r`row'c6",impvar)
  mat ivarfig5_r`row'c6=vecdiag(ivarfig5_r`row'c6)
  }
  
  

*** All these are bus_eq=bus_eq*wgt above...so undo that here
foreach v in bus_eq othfin nonfinasset mort_liab concr_liab nw {
	replace `v' = `v'/wgt
}

preserve
keep bus_eq othfin nonfinasset mort_liab concr_liab dfacat x1 nw

merge 1:1 x1 using `bsrep2009', gen(bsmerge)

drop if (bsmerge==2 | bsmerge==1)

tempfile boot_input
save `boot_input', replace

forvalues row = 1(1)6 {
  mat bsfig5_r`row'c1= J(1,1,.)
  mat bsfig5_r`row'c2= J(1,1,.)
  mat bsfig5_r`row'c3= J(1,1,.)
  mat bsfig5_r`row'c4= J(1,1,.)
  mat bsfig5_r`row'c5= J(1,1,.)
  mat bsfig5_r`row'c6= J(1,1,.)
}

/*---------------------------
Start the BS reps work.
Get the matrix of (999) top share estimates
---------------------------*/
drop _all
di in gr "(bootstrapping " _c
local j=1
while (`j'<=${reps}) {
  qui use `boot_input',clear
  qui keep if missing(mm`j')==0
  qui expand mm`j'

   tabstat bus_eq othfin nonfinasset mort_liab concr_liab nw [aw=wt1b`j'] , stats(sum) by(dfacat) save 
  qui tabstatmat fig5_`j'
  forvalues row = 1(1)6 {
	mat fig5_r`row'c1_`j' = fig5_`j'[`row',1]
	mat fig5_r`row'c2_`j' = fig5_`j'[`row',2]
	mat fig5_r`row'c3_`j' = fig5_`j'[`row',3]
	mat fig5_r`row'c4_`j' = fig5_`j'[`row',4]
	mat fig5_r`row'c5_`j' = fig5_`j'[`row',5]
	mat fig5_r`row'c6_`j' = fig5_`j'[`row',6]
  }  
  
  forvalues row = 1(1)6 {
   matrix bsfig5_r`row'c1 = bsfig5_r`row'c1 \ fig5_r`row'c1_`j'
   matrix bsfig5_r`row'c2 = bsfig5_r`row'c2 \ fig5_r`row'c2_`j'
   matrix bsfig5_r`row'c3 = bsfig5_r`row'c3 \ fig5_r`row'c3_`j'
   matrix bsfig5_r`row'c4 = bsfig5_r`row'c4 \ fig5_r`row'c4_`j'
   matrix bsfig5_r`row'c5 = bsfig5_r`row'c5 \ fig5_r`row'c5_`j'
   matrix bsfig5_r`row'c6 = bsfig5_r`row'c6 \ fig5_r`row'c6_`j'
  }
  
  di "." _c
  if mod(`j',25)==0{
  di "`j'"
  }
  local j=`j'+1
}


// Sampling variance of top wealth share
forvalues row = 1(1)6 {
  mata: svar=quadvariance(st_matrix("bsfig5_r`row'c1"))
  mata: st_matrix("svarbsfig5_r`row'c1",svar)
  mat svarbsfig5_r`row'c1=vecdiag(svarbsfig5_r`row'c1)

  mata: svar=quadvariance(st_matrix("bsfig5_r`row'c2"))
  mata: st_matrix("svarbsfig5_r`row'c2",svar)
  mat svarbsfig5_r`row'c2=vecdiag(svarbsfig5_r`row'c2)
  
  mata: svar=quadvariance(st_matrix("bsfig5_r`row'c3"))
  mata: st_matrix("svarbsfig5_r`row'c3",svar)
  mat svarbsfig5_r`row'c3=vecdiag(svarbsfig5_r`row'c3)
  
    mata: svar=quadvariance(st_matrix("bsfig5_r`row'c4"))
  mata: st_matrix("svarbsfig5_r`row'c4",svar)
  mat svarbsfig5_r`row'c4=vecdiag(svarbsfig5_r`row'c4)
  
    mata: svar=quadvariance(st_matrix("bsfig5_r`row'c5"))
  mata: st_matrix("svarbsfig5_r`row'c5",svar)
  mat svarbsfig5_r`row'c5=vecdiag(svarbsfig5_r`row'c5)

    mata: svar=quadvariance(st_matrix("bsfig5_r`row'c6"))
  mata: st_matrix("svarbsfig5_r`row'c6",svar)
  mat svarbsfig5_r`row'c6=vecdiag(svarbsfig5_r`row'c6)
}
  
// Combined Std Error due to Sampling and Imputation
forvalues row = 1(1)6 {
  mat sebsfig5_r`row'c1 =vecdiag(cholesky(diag(svarbsfig5_r`row'c1+(6/5)*ivarfig5_r`row'c1)))  
  mat sebsfig5_r`row'c2 =vecdiag(cholesky(diag(svarbsfig5_r`row'c2+(6/5)*ivarfig5_r`row'c2)))  
  mat sebsfig5_r`row'c3 =vecdiag(cholesky(diag(svarbsfig5_r`row'c3+(6/5)*ivarfig5_r`row'c3)))  
  mat sebsfig5_r`row'c4 =vecdiag(cholesky(diag(svarbsfig5_r`row'c4+(6/5)*ivarfig5_r`row'c4)))  
  mat sebsfig5_r`row'c5 =vecdiag(cholesky(diag(svarbsfig5_r`row'c5+(6/5)*ivarfig5_r`row'c5)))  
  mat sebsfig5_r`row'c6 =vecdiag(cholesky(diag(svarbsfig5_r`row'c6+(6/5)*ivarfig5_r`row'c6)))  
}  


// SCF panel means
di "SCF panel means "

mat fig5_mn = fig5_r1c1mn,fig5_r1c2mn,fig5_r1c3mn,fig5_r1c4mn,fig5_r1c5mn,fig5_r1c6mn \ fig5_r2c1mn,fig5_r2c2mn,fig5_r2c3mn,fig5_r2c4mn,fig5_r2c5mn,fig5_r2c6mn \ fig5_r3c1mn,fig5_r3c2mn,fig5_r3c3mn,fig5_r3c4mn,fig5_r3c5mn,fig5_r3c6mn \ fig5_r4c1mn,fig5_r4c2mn,fig5_r4c3mn,fig5_r4c4mn,fig5_r4c5mn,fig5_r4c6mn \ fig5_r5c1mn,fig5_r5c2mn,fig5_r5c3mn,fig5_r5c4mn,fig5_r5c5mn,fig5_r5c6mn \ fig5_r6c1mn,fig5_r6c2mn,fig5_r6c3mn,fig5_r6c4mn,fig5_r6c5mn,fig5_r6c6mn

mat colnames fig5_mn = bus_eq othfin nonfinasset mort_liab concr_liab nw 
mat li fig5_mn
mat li fig5

// SCF panel SEs
di "SCF panel SEs"

mat fig5_se = sebsfig5_r1c1,sebsfig5_r1c2,sebsfig5_r1c3,sebsfig5_r1c4,sebsfig5_r1c5,sebsfig5_r1c6 \ sebsfig5_r2c1,sebsfig5_r2c2,sebsfig5_r2c3,sebsfig5_r2c4,sebsfig5_r2c5,sebsfig5_r2c6 \ sebsfig5_r3c1,sebsfig5_r3c2,sebsfig5_r3c3,sebsfig5_r3c4,sebsfig5_r3c5,sebsfig5_r3c6 \ sebsfig5_r4c1,sebsfig5_r4c2,sebsfig5_r4c3,sebsfig5_r4c4,sebsfig5_r4c5,sebsfig5_r4c6 \ sebsfig5_r5c1,sebsfig5_r5c2,sebsfig5_r5c3,sebsfig5_r5c4,sebsfig5_r5c5,sebsfig5_r5c6 \ sebsfig5_r6c1,sebsfig5_r6c2,sebsfig5_r6c3,sebsfig5_r6c4,sebsfig5_r6c5,sebsfig5_r6c6

mat colnames fig5_se = bus_eq othfin nonfinasset mort_liab concr_liab nw 

// Display Standard errors, overall and by type
mat li fig5_se
  
restore



log close
